Page({
  data: {
    publishedArticles: [],
    totalViews: 0,
    totalLikes: 0
  },

  onLoad: function(options) {
    this.loadPublishedArticles();
  },

  onShow: function() {
    this.loadPublishedArticles();
    
    // 检查是否需要刷新数据（当从其他页面点赞回来时）
    const app = getApp();
    if (app.globalData && app.globalData.needRefreshMyPublished) {
      this.loadPublishedArticles();
      app.globalData.needRefreshMyPublished = false;
    }
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 加载发布的文章
  loadPublishedArticles: function() {
    const userPublishedArticles = wx.getStorageSync('userPublishedArticles') || [];
    
    // 计算统计数据
    let totalViews = 0;
    let totalLikes = 0;
    
    userPublishedArticles.forEach(article => {
      totalViews += article.viewCount || 0;
      totalLikes += article.likeCount || 0;
    });
    
    this.setData({
      publishedArticles: userPublishedArticles,
      totalViews: totalViews,
      totalLikes: totalLikes
    });
  },

  // 查看文章详情
  viewArticleDetail: function(e) {
    const articleId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${articleId}`
    });
  },

  // 编辑文章
  editArticle: function(e) {
    const articleId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '编辑功能开发中，敬请期待',
      showCancel: false,
      confirmText: '确定'
    });
  },

  // 删除文章
  deleteArticle: function(e) {
    const articleId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '删除后将无法恢复，确定要删除这篇文章吗？',
      confirmText: '删除',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.performDeleteArticle(articleId);
        }
      }
    });
  },

  // 执行删除文章
  performDeleteArticle: function(articleId) {
    wx.showLoading({
      title: '删除中...'
    });

    // 从用户发布文章中删除
    let userPublishedArticles = wx.getStorageSync('userPublishedArticles') || [];
    userPublishedArticles = userPublishedArticles.filter(article => String(article.id) !== String(articleId));
    wx.setStorageSync('userPublishedArticles', userPublishedArticles);

    // 删除相关评论
    const allComments = wx.getStorageSync('articleComments') || {};
    if (allComments[String(articleId)]) {
      delete allComments[String(articleId)];
      wx.setStorageSync('articleComments', allComments);
    }

    // 从收藏中删除（如果有人收藏了这篇文章）
    let collectedArticles = wx.getStorageSync('collectedArticles') || [];
    collectedArticles = collectedArticles.filter(article => String(article.id) !== String(articleId));
    wx.setStorageSync('collectedArticles', collectedArticles);

    wx.hideLoading();

    // 刷新页面数据
    this.loadPublishedArticles();
    
    // 通知其他页面更新
    this.notifyOtherPages();

    wx.showToast({
      title: '删除成功',
      icon: 'success'
    });
  },

  // 清空所有文章
  clearAllArticles: function() {
    if (this.data.publishedArticles.length === 0) {
      return;
    }

    wx.showModal({
      title: '确认清空',
      content: '将删除所有发布的文章，删除后无法恢复，确定要清空吗？',
      confirmText: '清空',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.performClearAllArticles();
        }
      }
    });
  },

  // 执行清空所有文章
  performClearAllArticles: function() {
    wx.showLoading({
      title: '清空中...'
    });

    // 获取所有要删除的文章ID
    const articleIds = this.data.publishedArticles.map(article => String(article.id));

    // 清空用户发布文章
    wx.setStorageSync('userPublishedArticles', []);

    // 删除所有相关评论
    const allComments = wx.getStorageSync('articleComments') || {};
    articleIds.forEach(articleId => {
      if (allComments[articleId]) {
        delete allComments[articleId];
      }
    });
    wx.setStorageSync('articleComments', allComments);

    // 从收藏中删除这些文章
    let collectedArticles = wx.getStorageSync('collectedArticles') || [];
    collectedArticles = collectedArticles.filter(article => 
      !articleIds.includes(String(article.id))
    );
    wx.setStorageSync('collectedArticles', collectedArticles);

    wx.hideLoading();

    // 刷新页面数据
    this.loadPublishedArticles();
    
    // 通知其他页面更新
    this.notifyOtherPages();

    wx.showToast({
      title: '清空成功',
      icon: 'success'
    });
  },

  // 去发布页面
  goToPublish: function() {
    wx.switchTab({
      url: '/pages/study/study'
    });
  },

  // 通知其他页面更新数据
  notifyOtherPages: function() {
    // 通知profile页面更新统计数据
    const app = getApp();
    if (app.globalData) {
      app.globalData.needUpdateStats = true;
      app.globalData.needRefreshCommunity = true;
    }
    
    // 直接获取当前页面栈中的profile页面并更新
    const pages = getCurrentPages();
    const profilePage = pages.find(page => page.route === 'pages/profile/profile');
    if (profilePage && profilePage.updateUserStats) {
      profilePage.updateUserStats();
    }

    // 通知community页面刷新数据
    const communityPage = pages.find(page => page.route === 'pages/community/community');
    if (communityPage && communityPage.loadAllArticles) {
      communityPage.loadAllArticles();
    }
  }
}) 